﻿using Ninject;
using SelfManagement.Account.Manager;
using SelfManagement.Database.POCO;
using SelfManagement.Mvc.Result;
using SelfManagement.Site.Models.Session;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SelfManagement.Site.Implementation.Account
{
    public class AccountService
    {
        [Inject]
        public UserManager UserManager { get; set; }

        public OperationResultData Login(LoginModel model)
        {
            OperationResultData result = new OperationResultData();
            result.RunWithTry(item =>
            {
                UserStatus status;
                bool vaild = UserManager.ValidateUser(model.UserName, model.Password, out status);
                if (!vaild)
                {
                    result.AddMessage("账户名或密码错误");
                    return;
                }
                else if (status == UserStatus.Locked)
                {
                    result.AddMessage("此账号被锁定，请稍后再试，或与客服联系。");
                }
                else
                {
                    var user = UserManager.Get(model.UserName);
                    if (status == UserStatus.Unactive)
                    {
                        //未激活账号，第一次访问自动激活
                        user.Status = UserStatus.Normal;
                        UserManager.Update(user);
                        result.AddSuccessMessage("账号激活成功！~~");
                    }
                    else
                    {
                        result.AddSuccessMessage("登录成功！");
                    }

                    var userSession = new UserSession(user);

                    //登录成功
                    UserSignIn(userSession, postModel.RememberMe);
                }
                

            });
            return result;
        }
    }
}
